<?php if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 *
 * @abstract 订单管理
 * @author zxj
 *
 */
class Order_new extends MY_Controller
{
    private $t_order = 'mt_order';  //订单表

    function __construct()
    {
        parent::__construct();
    }


    /**
     * 更新订单
     */
    function reSetOrder()
    {
        $orderList = $this->common_model->selectCustom('mt_order');
        foreach ($orderList as $rs) {
            //清除报价
            $this->common_model->clearOrder($rs['id']);
            //生成运费
            $this->common_model->setShippingPrice($rs['id']);
            //产品列表
            $productList = $this->common_model->selectCustom('mt_product' , array('oid' => $rs['id']));
            foreach ($productList as $row) {
                //清除产品报价
                $this->common_model->clearProduct($row['id']);
                //生成产品费用
                $this->common_model->setProductPrice($row['id']);
            }
        }
    }


    /**
     * 维修列表
     */
    function index()
    {
        //获取表单数据
        $data = $formField = gp();
        //#查询条件
        $searchStr = 'orders/Order_new/index/?';
        $keywordOrder = trim($data['keywordOrder']);
        $keywordProduct = trim($data['keywordProduct']);
        if ($keywordOrder) {
            if (filter_var($keywordOrder , FILTER_VALIDATE_EMAIL)) {
                $where = 'where o.consumer_email = \'' . $keywordOrder . '\' ';
            }
            else {
                $where = 'where (o.order_num like \'%' . $keywordOrder . '%\' or o.source_oid like \'%' . $keywordOrder . '%\' or o.shipinTrack like \'%' . $keywordOrder . '%\') ';
            }
            $searchStr .= 'keywordOrder=' . $keywordOrder;
        }
        if ($keywordProduct) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= '(p.source_id_order like \'%' . $keywordProduct . '%\' or p.productSku like \'%' . $keywordProduct . '%\' or p.imei like \'%' . $keywordProduct . '%\') ';
            $searchStr .= '&keywordProduct=' . $keywordProduct;
        }
        //状态
        $status_id = intval($data['status_id']);
        if ($status_id) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'p.status_id=' . $status_id;
            $searchStr .= '&status_id=' . $status_id;
        }
        //服务中心
        $service_center = intval($data['service_center']);
        if ($service_center) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'o.service_center=' . $service_center;
            $searchStr .= '&service_center=' . $service_center;
        }
        //服务类型
        $service_type = intval($data['service_type']);
        if ($service_type) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'o.service_type=' . $service_type;
            $searchStr .= '&service_type=' . $service_type;
        }
        //卖家编号
        $merchant_num = intval($data['merchant_num']);
        if ($merchant_num) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'o.merchant_num=' . $merchant_num;
            $searchStr .= '&merchant_num=' . $merchant_num;
        }
        //品牌编号
        $brandCustomerNum = intval($data['brandCustomerNum']);
        if ($brandCustomerNum) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'p.brandCustomerNum=' . $brandCustomerNum;
            $searchStr .= '&brandCustomerNum=' . $brandCustomerNum;
        }
        //角色
        $role = $this->users['role'];
        $data['role'] = $role;
        $point = $this->users['service_center'];
        if ($role != 'admin' && !$service_center && $point) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'o.service_center=' . $point;
        }
        //默认select设置
        $optStatus[$status_id] = 'selected';
        $data['optStatus'] = $optStatus;
        $optServiceCenter[$service_center] = 'selected';
        $data['optServiceCenter'] = $optServiceCenter;
        $optServiceType[$service_type] = 'selected';
        $data['optServiceType'] = $optServiceType;
        $optMerchant[$merchant_num] = 'selected';
        $data['optMerchant'] = $optMerchant;
        $optBrand[$brandCustomerNum] = 'selected';
        $data['optBrand'] = $optBrand;
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $sql = 'select p.id,p.oid,p.status_id,p.category_id,p.productSku,p.imei,p.brandCustomerNum,p.imei,p.add_user,p.add_time,p.available,p.source_id_order,
                o.order_num,o.source_oid,o.website_origin,o.service_center,o.service_type,o.consumer_email,o.isSync_sf,o.status_id as sId,
                o.merchant_num,o.create_time,o.shipinTrack
                from mt_product p left join mt_order o on p.oid = o.id ' . $where;
        $config['total_rows'] = $this->common_model->getQuery($sql , 'num_rows');
        $config['per_page'] = 20;
        $page = max(1 , intval($data['page']));
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $offset = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $sql .= ' order by o.create_time desc limit ' . $offset . ',' . $config['per_page'] . ' ';
        $dataList = $this->common_model->getQuery($sql , 'result_array');
        $data['show_pages'] = $this->pagination->create_links();
        //重构数据
        foreach ($dataList as $key => &$rs) {
            $serviceType = $this->common_model->selectFirst('mt_service_type' , array('id' => $rs['service_type']));
            $statusFirst = $this->common_model->selectFirst('mt_product_status' , array('id' => $rs['status_id']));
            $rs['serviceName'] = $serviceType['name_' . $this->curLang];
            $rs['statusName'] = $statusFirst['name_' . $this->curLang];
            $rs['add_time'] = 'updateDate:' . date('Y-m-d H:i:s' , $rs['add_time']);
            $rs['nextAct'] = $this->common_model->flowAction($rs['id'] , $rs['status_id']);
        }
        unset($rs);
        $data['dataList'] = $dataList;
        //查询服务站点
        if ($role == 'admin') {
            $serviceCenterList = $this->common_model->selectall('mt_service_center');
            $data['serviceCenterList'] = $serviceCenterList;
        }
        //查询服务类型
        $serviceTypeList = $this->common_model->selectall('mt_service_type');
        $data['serviceTypeList'] = $serviceTypeList;
        //查询所有状态
        $statusList = $this->common_model->selectCustom('mt_product_status');
        $data['statusList'] = $statusList;
        //查询卖家
        $merchantList = $this->common_model->selectCustom('mt_customers' , array('type' => 1));
        $data['merchantList'] = $merchantList;
        //查询品牌
        $brandList = $this->common_model->selectCustom('mt_customers' , array('type' => 2));
        $data['brandList'] = $brandList;
        if ($this->debug) {
            gsh_output($data);
        }
        //视图以及样式
        $data['curLang'] = $this->curLang;
        $this->load->view('defaults/order_new' , $data);
        $this->load->view('defaults/common/footer');
    }


    /**
     * 查看订单详情
     * @param string $id
     * @return mixture
     */
    function inDetails($id = '')
    {
        $id = empty($id) ? gp('id') : $id;
        $data['role'] = $this->users['role'];
        //获取订单信息
        $orderFirst = $this->common_model->selectFirst($this->t_order , array('id' => $id));
        $serviceCenter = $this->common_model->selectFirst('mt_service_center' , array('id' => $orderFirst['service_center']));
        $serviceType = $this->common_model->selectFirst('mt_service_type' , array('id' => $orderFirst['service_type']));
        $statusFirst = $this->common_model->selectFirst('mt_order_status' , array('id' => $orderFirst['status_id']));
        $websiteFirst = $this->common_model->selectFirst('mt_order_website' , array('id' => $orderFirst['source_site']));
        $orderFirst['serviceCenterName'] = $serviceCenter['name_' . $this->curLang];
        $orderFirst['tax'] = sprintf('%s%%' , $serviceCenter['tax'] * 100);
        $orderFirst['serviceTypeName'] = $serviceType['name_' . $this->curLang];
        $orderFirst['statusName'] = $statusFirst['name_' . $this->curLang];
        $orderFirst['websiteName'] = $websiteFirst['name'];
        $consumer_num = $orderFirst['merchant_num'] ? $orderFirst['merchant_num'] : $orderFirst['consumer_num'];
        $consumerFirst = $this->common_model->selectFirst('mt_customers' , array('id' => $consumer_num));
        $consumerFirst['name'] = $consumerFirst['name_' . $this->curLang] ? $consumerFirst['name_' . $this->curLang] : $consumerFirst['name'];
        $data['consumerFirst'] = $consumerFirst;
        //#产品列表
        $productList = $this->common_model->selectCustom('mt_product' , array('oid' => $id));
        foreach ($productList as &$rs) {
            $categoryFirst = $this->common_model->selectFirst('mt_product_category' , array('id' => $rs['category_id']));
            $rs['category_name'] = $categoryFirst['name_' . $this->curLang];
            if ($rs['available'] == 2) {
                $rs['status_name'] = '<span style="color: red;">hold</span>';
                continue;
            }
            else {
                $statusFirst = $this->common_model->selectFirst('mt_product_status' , array('id' => $rs['status_id']));
                $rs['status_name'] = $statusFirst['name_' . $this->curLang];
            }
        }
        unset($rs);
        $data['productList'] = $productList;
        //#维修轨迹
        $trackList = $this->common_model->selectCustom('mt_order_track' , array('oid' => $id));
        foreach ($trackList as &$rs) {
            $status = $this->common_model->selectFirst('mt_order_status' , array('id' => $rs['end_sid']));
            $rs['status_name'] = $status['name_' . $this->curLang];
            $rs['is_sync'] = $rs['is_sync'] ? 'Yes' : 'No';
            $rs['add_time'] = date('Y-m-d H:i:s' , $rs['add_time']);
        }
        unset($rs);
        $data['trackList'] = $trackList;
        //#订单信息
        $orderFirst['add_time'] = date('Y-m-d H:i:s' , $orderFirst['add_time']);
        if (isset($orderFirst['delivery_service'])) {
            $orderFirst['delivery_service'] = $orderFirst['delivery_service'] ? lang('order_kd') : lang('order_khzq');
        }
        if (isset($orderFirst['pickup_service'])) {
            $orderFirst['pickup_service'] = $orderFirst['pickup_service'] ? lang('order_khzf') : lang('order_smqj');
        }
        $orderFirst['storeOrShip'] = $orderFirst['storeOrShip'] ? lang('order_fh') : lang('order_rk');
        $data['orderFirst'] = $orderFirst;

        if ($this->debug) {
            gsh_output($data);
        }
        //views
        $this->breadcrumb->append_crumb(array('url' => 'orders/Order_new/inDetails/' . $id , 'name' => lang('order_ddxq')));
        $this->load->view('defaults/order_inDetail_new' , $data);
        $this->load->view('defaults/common/footer');
    }


    /**
     * 修改订单
     * @param string $id
     */
    function edit($id = '')
    {
        //表单处理
        $data['post_type'] = __FUNCTION__;
        //接收数据
        $id = intval($id) ? intval($id) : gp('id');
        $data['id'] = $id;
        $data['role'] = $this->users['role'];
        $orderFirst = $this->common_model->selectFirst($this->t_order , array('id' => $id));
        if (!$orderFirst) {
            show_error('this order not found');
        }
        //判断是否修改数据
        $formData = gp();
        if ($formData['submits']) {
            $formData['add_user'] = $this->users['account'];
            $inData = array();
            foreach ($formData as $key => $val) {
                if (array_key_exists($key , $orderFirst) && $orderFirst[$key] != $val) {
                    $inData[$key] = $val;
                }
            }
            if ($inData) {
                $this->common_model->update($this->t_order , $inData , array('id' => $id));
                if (!$orderFirst['is_pay']) {
                    $this->common_model->setOrderPrice($id);
                }
            }
            redirect('orders/Order_new/inDetails/' . $id);
        }
        else {
            $serviceCenter = $this->common_model->selectFirst('mt_service_center' , array('id' => $orderFirst['service_center']));
            $serviceType = $this->common_model->selectFirst('mt_service_type' , array('id' => $orderFirst['service_type']));
            $orderFirst['serviceCenter_name'] = $serviceCenter['name_' . $this->curLang];
            $orderFirst['serviceType_name'] = $serviceType['name_' . $this->curLang];
            $data['orderFirst'] = $orderFirst;
            //获取状态
            $statusList = $this->common_model->selectCustom('mt_order_status');
            $data['statusList'] = $statusList;
            //default
            $ckdAvailable[$orderFirst['available']] = 'checked';
            $data['ckdAvailable'] = $ckdAvailable;
            $optStatus[$orderFirst['status_id']] = 'selected';
            $data['optStatus'] = $optStatus;
            $ckdDelivery[$orderFirst['delivery_service']] = 'checked';
            $data['ckdDelivery'] = $ckdDelivery;
            $ckdPickup[$orderFirst['pickup_service']] = 'checked';
            $data['ckdPickup'] = $ckdPickup;
            $ckdPackage[$orderFirst['is_package']] = 'checked';
            $data['ckdPackage'] = $ckdPackage;
            //views
            $data['curLang'] = $this->curLang;
            $this->breadcrumb->append_crumb(array('url' => 'orders/Order_new/inDetails/' . $id , 'name' => lang('order_ddxq')));
            $this->load->view('defaults/order_post_new' , $data);
            $this->load->view('defaults/common/footer');
        }
    }


    /**
     * 删除订单
     * @param string $id
     * @param string $page
     */
    function del($id = '' , $page = '')
    {
        if ($this->users['role'] != 'admin')
            show_error('admin role');
        $id = intval($id);
        //clear product
        $where = array('oid' => $id);
        $this->common_model->delete('mt_product_log' , $where);
        $this->common_model->delete('mt_product_parts' , $where);
        $this->common_model->delete('mt_product_track' , $where);
        $this->common_model->delete('mt_product' , $where);
        //clear order
        $where = array('id' => $id);
        $this->common_model->delete('mt_order_log' , $where);
        $this->common_model->delete('mt_order_track' , $where);
        $this->common_model->delete('mt_order' , $where);
        redirect(blang_url('orders/Order_new/index/?page=' . intval($page)));
    }


    /**
     * 刷新订单价格
     * @param string $id
     * @return bool
     */
    function reloadPrice($id = '')
    {
        $id = intval($id);
        $this->common_model->setOrderPrice($id);
        if (!$this->debug) {
            redirect('orders/Order_new/inDetails/' . $id);
        }
        return true;
    }


    /**
     * 推送订单到SF
     * @param string $id
     */
    function pushSF($id = '')
    {
        $this->load->model('salesforce_model' , 'sfModel');
        $result = $this->sfModel->oms_to_sf001($id);
        if ($result['status']) {
            $this->common_model->update('mt_order' , array('isSync_sf' => 1) , array('id' => $id));
        }
        if (is_array($result)) {
            gsh_output($result);
        }
        else {
            echo $result;
        }
    }

   


}
